//
//  PersonInboxViewController.m
//  MOPAI
//
//  Created by Lixiaoyong on 13-4-10.
//  Copyright (c) 2013年 . All rights reserved.
//

#import "PersonInboxViewController.h"

#import <QuartzCore/QuartzCore.h>
#import "InterfaceDefine.h"
#import "JSONKit.h"
#import "FMManager.h"
#import "SVPullToRefresh.h"
#import "UIImageView+WebCache.h"
#import "DLog.h"
#import "SecondViewController.h"

#define kImageTagBase 1000

#define kPageSize (@"20")
#define kInboxKey1 (@"createTimeStr")
#define kInboxKey2 (@"jobsId")
#define kInboxKey3 (@"jobsInformation")

#define kPersonInboxKey1 (@"createTimeStr")
#define kPersonInboxKey2 (@"modelsAvatarstr")
#define kPersonInboxKey3 (@"modelsId")
#define kPersonInboxKey5 (@"userId")
#define kPersonInboxKey4 (@"modelsName")
#define kPersonInboxKey6 (@"userType")
#define kLowSize (4)
#define kFont ([UIFont systemFontOfSize:16.0])

@interface PersonInboxViewController ()
{
    MBProgressHUD *mHUD;
}
@property (nonatomic,retain) NSMutableArray *personInboxArrayDatas;  //个人收件箱数据
@property (nonatomic,assign) BOOL personIsHaveData;     //是否还有数据
@property (nonatomic,assign) int personPageNo;  //页码
@property (nonatomic,retain) UIView *headerView;
@property (nonatomic,retain) NSTimer *personTimer;
@end

@implementation PersonInboxViewController
@synthesize jobDics;
@synthesize delegate;
@synthesize personInboxArrayDatas;
@synthesize personIsHaveData,personPageNo;
@synthesize headerView;
@synthesize personTimer;

#pragma mark - system methods

- (void)dealloc
{
    self.jobDics = nil;
    self.delegate = nil;
    self.personInboxArrayDatas = nil;
    self.headerView = nil;
    [self.personTimer invalidate];
    self.personTimer = nil;
    [super dealloc];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self)
    {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[UIBarButtonItem appearance] setTintColor:[UIColor blackColor]];
    
    self.view.backgroundColor = [UIColor colorWithHue:26.0/255 saturation:26.0/255 brightness:26.0/255 alpha:1.0];
    
    UIBarButtonItem *rightButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(personInboxEditAction)] autorelease];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.personPageNo = 0;
    self.personInboxArrayDatas = [[[NSMutableArray alloc] init] autorelease];
    [self getPersonDatas];
    
    //下拉事件
    [self.tableView addInfiniteScrollingWithActionHandler:^{
        
        if(self.personIsHaveData)
        {
            self.personPageNo = self.personPageNo + 1;
            self.personTimer = [NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:@selector(getPersonDatas) userInfo:nil repeats:NO];
        }
        else
        {
            [self.tableView.infiniteScrollingView stopAnimating];
        }
    }];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    FMManager *fm = [FMManager sharedInstance];
    if(fm.updateInboxCtrl)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - private methods

-(void)personInboxEditAction
{
    UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"删除收件"message:@""delegate:self cancelButtonTitle:@"取消"otherButtonTitles: @"确定",nil];
    [alert show];
    [alert release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    DLog(@"%i",buttonIndex);
    if(buttonIndex == 0)
    {
        return;
    }
    else if(buttonIndex == 1)
    {
        [self deleteJob];
    }
}

-(void)deleteJob
{
    NSString *jobsId = [self.jobDics objectForKey:@"jobsId"];
    if(jobsId)
    {
        mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        [self.navigationController.view addSubview:mHUD];
        mHUD.delegate = self;
        [mHUD show:YES];
        
        NSString *urlStr = [NSString stringWithFormat:@"%@/%@",kHttpHost,kDeleteJobInfo];
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlStr]];
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setValue:jobsId forKey:@"jobsId"];
        NSString *postStr = [dic JSONString];
        [dic release];
        [request appendPostData:[postStr dataUsingEncoding:NSUTF8StringEncoding]];
        [request setRequestMethod:@"POST"];
        request.delegate = self;
        [request startAsynchronous];
    }
}

//获取数据
- (void)getPersonDatas
{
    NSString *urlStr = [NSString stringWithFormat:@"%@/%@",kHttpHost,kGetPersonInbox];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlStr]];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:[self.jobDics objectForKey:kInboxKey2] forKey:kInboxKey2];
    [dic setValue:[NSString stringWithFormat:@"%d",self.personPageNo] forKey:@"startPage"];
    [dic setValue:kPageSize forKey:@"pageSize"];
    NSString *postStr = [dic JSONString];
    [dic release];
    [request appendPostData:[postStr dataUsingEncoding:NSUTF8StringEncoding]];
    [request setRequestMethod:@"POST"];
    request.delegate = self;
    [request startAsynchronous];
}

//获取高度
- (CGFloat)computerLableHeight
{
    NSString *content = [self.jobDics objectForKey:kInboxKey3];
    float width = self.view.frame.size.width;
    CGSize size = [content sizeWithFont:kFont constrainedToSize:CGSizeMake(width-30, 1000) lineBreakMode:NSLineBreakByTruncatingTail];
    return size.height;
}

//重组数据
- (void)structureArray:(NSMutableArray *)array
{
    int number = kLowSize;
    int addNumber = 0;
    int beforeCount = self.personInboxArrayDatas.count;
    if (beforeCount > 0 && array.count > 0)
    {
        NSMutableArray *lastArray = [self.personInboxArrayDatas objectAtIndex:(beforeCount - 1)];
        int lastCount = lastArray.count;
        if (lastCount < kLowSize)
        {
            int tag = 0;
            for (int i=lastCount; i<number; i++)
            {
                tag = i - lastCount;
                if (tag > (array.count - 1))
                {
                    break;
                }
                
                NSDictionary *dic = [array objectAtIndex:(i-lastCount)];
                [lastArray addObject:dic];
                addNumber++;
            }
        }
        [self.personInboxArrayDatas replaceObjectAtIndex:(beforeCount-1) withObject:lastArray];
    }
    
    for (int i=0; i<addNumber; i++)
    {
        [array removeObjectAtIndex:0];
    }
    
    int count = array.count;
    int row = count / number;
    int last = count % number;
    for (int i=0; i<=row; i++)
    {
        NSMutableArray *rowArray = [[NSMutableArray alloc] init];
        for (int j=0; j<number; j++)
        {
            if (i==row && j==last)
            {
                break;
            }
            
            NSDictionary *dic = [array objectAtIndex:(number * i + j)];
            [rowArray addObject:dic];
        }
        if (rowArray.count > 0)
        {
            [self.personInboxArrayDatas addObject:rowArray];
        }
        [rowArray release];
    }
    [self nslogArray];
    [self.tableView reloadData];
}

- (void)nslogArray
{
    for (int i=0; i<self.personInboxArrayDatas.count; i++)
    {
        NSArray *array = [self.personInboxArrayDatas objectAtIndex:i];
        for (int j=0; j<array.count; j++)
        {
            NSDictionary *dic = [array objectAtIndex:j];
            DLog(@"dic = %@",dic);
        }
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //return 2;
    if(self.personInboxArrayDatas && self.personInboxArrayDatas.count > 0)
    {
        return 2;
    }
    else
    {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1)
    {
        if(self.personInboxArrayDatas)
        {
            int count = self.personInboxArrayDatas.count;
            DLog(@"count = %d",count);
            return count;
        }
        else
        {
            return 0;
        }
        
    }
    else
    {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
    {
        static NSString *personInboxCell = @"personInboxCell";
        ThreeImageCell *cell = [tableView dequeueReusableCellWithIdentifier:personInboxCell];
        if (cell == nil)
        {
            cell = [[[ThreeImageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:personInboxCell canCheck:NO] autorelease];
        }
        
        [self nslogArray];
        int row = indexPath.row;
        NSMutableArray *item = [self.personInboxArrayDatas objectAtIndex:row];
        for (int i=0; i<item.count; i++)
        {
            NSDictionary *dic = [item objectAtIndex:i];
            NSString *urlStr = [dic objectForKey:kPersonInboxKey2];
            DLog(@"urlStr = %@",urlStr);
            TouchImageView *touchImage = [cell.imageViews objectAtIndex:i];
            
            if (row > 0)
            {
                CGRect rect = touchImage.frame;
                rect.origin.y = 1.0;
                touchImage.frame = rect;
            }
            
            touchImage.delegate = self;
            touchImage.tag = row * kLowSize +i + kImageTagBase;
            [touchImage setImageWithURL:[NSURL URLWithString:urlStr]
                       placeholderImage:[UIImage imageNamed:@"touxiang@2x.png"]];
            touchImage.hidden = NO;
        }
        
        return cell;
    }
    else
    {
        return nil;
    }
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        float height = [self computerLableHeight];
        return height + 50;
    }
    else
    {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
    {
        float space = (indexPath.row == 1) ? 6.0 : 4.0;
        return ((tableView.frame.size.width - 10) / 4.0 + space);
    }
    else
    {
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        if (self.headerView == nil)
        {
            float height = [self computerLableHeight];
            CGRect rect = CGRectMake(0, 0, tableView.frame.size.width, height+40);
            self.headerView = [[[UIView alloc] initWithFrame:rect] autorelease];
            self.headerView.backgroundColor = [UIColor clearColor];
            
            rect = CGRectMake(10, 5, rect.size.width-20, rect.size.height-10);
            UIView *subView = [[[UIView alloc] initWithFrame:rect] autorelease];
            subView.layer.cornerRadius = 6.0;
            subView.backgroundColor = [UIColor lightGrayColor];
            [self.headerView addSubview:subView];
            
            rect = CGRectMake(10, 5, rect.size.width-20, height);
            UILabel *content = [[[UILabel alloc] initWithFrame:rect] autorelease];
            content.backgroundColor = [UIColor clearColor];
            content.font = kFont;
            content.numberOfLines = 0;
            content.lineBreakMode = NSLineBreakByTruncatingTail;
            content.text = [self.jobDics objectForKey:kInboxKey3];
            [subView addSubview:content];
            
            rect.origin.y = rect.origin.y + rect.size.height;
            rect.size.height = 25;
            UILabel *date = [[[UILabel alloc] initWithFrame:rect] autorelease];
            date.backgroundColor = [UIColor clearColor];
            date.font = [UIFont systemFontOfSize:12.0];
            date.text = [self.jobDics objectForKey:kInboxKey1];
            date.textColor = [UIColor grayColor];
            [subView addSubview:date];
        }
        
        return self.headerView;
    }
    else
    {
        return nil;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - TouchImageViewDelegate

- (void)clickImageView:(TouchImageView *)imageView
{
    int index = imageView.tag - kImageTagBase;
    int low = index % kLowSize;
    int row = index / kLowSize;
    NSArray *array = [self.personInboxArrayDatas objectAtIndex:row];
    NSDictionary *dic = [array objectAtIndex:low];
    NSString *modelsId = [dic objectForKey:@"modelsId"];
    NSNumber *userId = [dic objectForKey:@"userId"];
    NSString *usertype = [NSString stringWithFormat:@"%@",[dic objectForKey:kPersonInboxKey6]];
    
    SecondViewController *ctrl = [[[SecondViewController alloc] init] autorelease];
    ctrl.editType=@"isWorker";
    ctrl.modelId = modelsId;
    ctrl.userId = [userId stringValue];
    ctrl.title = @"个人资料";
    ctrl.userIdentify = usertype;
    [self.navigationController pushViewController:ctrl animated:YES];
    [ctrl myRefeash];
}

-(void) viewListing:(TouchImageView *) imageView
{
    
}

-(void) editListing:(TouchImageView *) imageView
{
    
}

#pragma mark - ASIHTTPRequestDelegate

- (void)requestFailed:(ASIHTTPRequest *)request
{
    if(mHUD == nil)
    {
        mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        [self.navigationController.view addSubview:mHUD];
        mHUD.delegate = self;
        [mHUD show:YES];
    }
    mHUD.mode =MBProgressHUDModeText;
    mHUD.labelText = @"网络链接失败";
    [mHUD hide:YES afterDelay:1.5];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    
    NSString *urlStr = [NSString stringWithFormat:@"%@",request.url];
    NSString *action = @"";
    if (urlStr.length > 0)
    {
        NSArray *array = [urlStr componentsSeparatedByString:@"/"];
        action = [array objectAtIndex:(array.count - 1)];
    }
    DLog(@"%@",action);
    
    NSData *data = [request responseData];
    NSArray *array = [data objectFromJSONData];
    
    if([action isEqualToString:(kDeleteJobInfo)])
    {
        NSString *item0 = [array objectAtIndex:0];
        if(![item0 isEqualToString:kResponseOk])
        {
            if(mHUD == nil)
            {
                mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
                [self.navigationController.view addSubview:mHUD];
                mHUD.delegate = self;
                [mHUD show:YES];
            }
            mHUD.mode =MBProgressHUDModeText;
            mHUD.labelText = @"删除失败";
            [mHUD hide:YES afterDelay:1.5];
            return;
        }
        else
        {
            if(mHUD == nil)
            {
                mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
                [self.navigationController.view addSubview:mHUD];
                mHUD.delegate = self;
                [mHUD show:YES];
            }
            mHUD.mode =MBProgressHUDModeText;
            mHUD.labelText = @"删除成功";
            [mHUD hide:YES afterDelay:1];
        }
    }
    else
    {
        NSString *item0 = [array objectAtIndex:0];
        if(![item0 isEqualToString:kResponseOk])
        {
            if(mHUD == nil)
            {
                mHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
                [self.navigationController.view addSubview:mHUD];
                mHUD.delegate = self;
                [mHUD show:YES];
            }
            mHUD.mode =MBProgressHUDModeText;
            mHUD.labelText = @"收件箱为空";
            [mHUD hide:YES afterDelay:1.5];
            return;
        }
        
        NSDictionary *datadic = [array objectAtIndex:1];
        NSArray *tempArray = [datadic objectForKey:@"data"];
        if(tempArray.count == 0)
        {
            [self.tableView.infiniteScrollingView stopAnimating];
            self.personIsHaveData = NO;
            return;
        }
        else
        {
            self.personIsHaveData = YES;
        }
        
        NSMutableArray *reslutArray = [[[NSMutableArray alloc] init] autorelease];
        
        for (int i=0; i<tempArray.count; i++)
        {
            NSDictionary *dic = [tempArray objectAtIndex:i];
            NSString *imageUrl = [dic objectForKey:kPersonInboxKey2];
            if (imageUrl && imageUrl.length > 0)
            {
                NSMutableDictionary *dicCopy = [[NSMutableDictionary alloc] init];
                NSString *modelId = [dic objectForKey:kPersonInboxKey3];
                NSString *userId = [dic objectForKey:kPersonInboxKey5];
                imageUrl = [NSString stringWithFormat:@"%@/%@/%@/small_%@",kHttpHost,@"photo",userId,imageUrl];
                DLog(@"imageurl = %@",imageUrl);
                [dicCopy setValue:[dic objectForKey:kPersonInboxKey1] forKey:kPersonInboxKey1];
                [dicCopy setValue:imageUrl forKey:kPersonInboxKey2];
                [dicCopy setValue:modelId forKey:kPersonInboxKey3];
                [dicCopy setValue:[dic objectForKey:kPersonInboxKey4] forKey:kPersonInboxKey4];
                [dicCopy setValue:userId forKey:kPersonInboxKey5];
                [dicCopy setValue:[dic objectForKey:kPersonInboxKey6] forKey:kPersonInboxKey6];
                [reslutArray addObject:dicCopy];
                [dicCopy release];
            }
        }
        
        [self structureArray:reslutArray];
    }
        
    
}

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
	// Remove HUD from screen when the HUD was hidded
    if([mHUD.labelText isEqualToString:@"删除成功"])
    {
        if(self.delegate)
        {
            [self.delegate deleteOK];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
    
	[mHUD removeFromSuperview];
	[mHUD release];
	mHUD = nil;
}
@end